package com.shawn.integeration.batch.csv;

import com.shawn.integeration.batch.model.vo.CsvVo;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;

import javax.annotation.Resource;

/**
 * @author shawn
 * @description: Csv 文件读取配置
 * @date 2024/1/7
 */
//@Configuration
public class CsvFileItemReaderJobBatchConfig {
    /**
     * 任务创建工厂
     */
    @Resource
    private JobBuilderFactory jobFactory;

    /**
     * 步骤创建工厂
     */
    @Resource
    private StepBuilderFactory stepFactory;

    @Bean
    public Job fileItemReaderJob() {
        return jobFactory.get("fileItemReaderJob")
                .start(fileItemReaderJobStep())
                .build();
    }

    private Step fileItemReaderJobStep() {
        return stepFactory.get("csvItemReaderJobStep")
                .<CsvVo, CsvVo>chunk(2)
                .reader(csvItemReader())
                .writer(list -> list.forEach(System.out::println))
                .build();
    }

    public FlatFileItemReader<CsvVo> csvItemReader() {
        FlatFileItemReader<CsvVo> csvItemReader = new FlatFileItemReader<>();
        // 文件地址
        csvItemReader.setResource(new ClassPathResource("static/test.csv"));
        // 忽略第一行
        csvItemReader.setLinesToSkip(1);
        csvItemReader.setLineMapper(new DefaultLineMapper<CsvVo>() {{
            setLineTokenizer(new DelimitedLineTokenizer() {{
                setNames(new String[]{"name", "age"});
            }});
            setFieldSetMapper(new BeanWrapperFieldSetMapper<CsvVo>() {{
                setTargetType(CsvVo.class);
            }});
        }});
        return csvItemReader;
    }


}
